import { defineStore } from "pinia";
import { ref, computed } from "vue";

// 初始状态
function initState() {
    return {
        // 用户基本信息
        basicInfo: {
            id: null,
            username: "",
            phone: "",
            email: "",
            realName: "",
            idCard: "",
            avatar: "",
            status: null,
            lastLoginTime: null,
            lastLoginIp: "",
            createTime: null,
            updateTime: null
        },
        // 用户详细信息
        detailInfo: {
            name: "",
            idCardFrontImage: "",
            idCardBackImage: "",
            idCardHandImage: "",
            alipayAccount: "",
            alipayScore: null,
            education: null,
            companyName: "",
            position: "",
            companyPhone: "",
            workYears: null,
            companyAddress: "",
            monthlyIncome: null,
            residenceAddress: "",
            contact1Name: "",
            contact1Phone: "",
            contact1Relation: null,
            contact2Name: "",
            contact2Phone: "",
            contact2Relation: null,
            otherData: null // 补充资料，JSON格式
        },
        // 是否已加载数据
        isLoaded: false,
        // 加载状态
        loading: false
    };
}

export const useUserInfoStore = defineStore("userInfoStore", () => {
    // 状态
    const state = ref(initState());

    // 计算属性
    const isLoaded = computed(() => state.value.isLoaded);
    const loading = computed(() => state.value.loading);
    const hasIdentityInfo = computed(() => 
        !!state.value.detailInfo.name && 
        !!state.value.detailInfo.idCardFrontImage && 
        !!state.value.detailInfo.idCardBackImage && 
        !!state.value.detailInfo.idCardHandImage
    );
    const hasPersonalInfo = computed(() => 
        !!state.value.detailInfo.alipayAccount && 
        !!state.value.detailInfo.companyName && 
        !!state.value.detailInfo.companyPhone && 
        !!state.value.detailInfo.companyAddress &&
        !!state.value.detailInfo.contact1Name && 
        !!state.value.detailInfo.contact1Phone && 
        !!state.value.detailInfo.contact1Relation
    );
    const hasContactInfo = computed(() => 
        !!state.value.detailInfo.contact2Name && 
        !!state.value.detailInfo.contact2Phone && 
        !!state.value.detailInfo.contact2Relation
    );
    
    // 是否有补充资料
    const hasOtherData = computed(() => 
        !!state.value.detailInfo.otherData && 
        Object.keys(JSON.parse(state.value.detailInfo.otherData)).length > 0
    );



    // 设置用户信息
    function setUserInfo(userData) {
        if (!userData) return;
        
        state.value.loading = true;
        
        try {
            // 更新基本信息
            if (userData.basicInfo) {
                state.value.basicInfo = {
                    ...state.value.basicInfo,
                    ...userData.basicInfo
                };
            } else {
                // 兼容直接传入用户基本信息的情况
                const basicInfoKeys = [
                    'id', 'username', 'phone', 'email', 'realName', 
                    'idCard', 'avatar', 'status', 'lastLoginTime', 
                    'lastLoginIp', 'createTime', 'updateTime'
                ];
                
                const basicInfo = {};
                basicInfoKeys.forEach(key => {
                    if (userData[key] !== undefined) {
                        basicInfo[key] = userData[key];
                    }
                });
                
                if (Object.keys(basicInfo).length > 0) {
                    state.value.basicInfo = {
                        ...state.value.basicInfo,
                        ...basicInfo
                    };
                }
            }
            
            // 更新详细信息
            if (userData.detailInfo) {
                state.value.detailInfo = {
                    ...state.value.detailInfo,
                    ...userData.detailInfo
                };
            } else {
                // 兼容直接传入用户详细信息的情况
                const detailInfoKeys = [
                    'name', 'idCardFrontImage', 'idCardBackImage', 'idCardHandImage',
                    'alipayAccount', 'alipayScore', 'education', 'companyName',
                    'position', 'companyPhone', 'workYears', 'companyAddress',
                    'monthlyIncome', 'residenceAddress', 'contact1Name', 'contact1Phone',
                    'contact1Relation', 'contact2Name', 'contact2Phone', 'contact2Relation',
                    'otherData'
                ];
                
                const detailInfo = {};
                detailInfoKeys.forEach(key => {
                    if (userData[key] !== undefined) {
                        detailInfo[key] = userData[key];
                    }
                });
                
                if (Object.keys(detailInfo).length > 0) {
                    state.value.detailInfo = {
                        ...state.value.detailInfo,
                        ...detailInfo
                    };
                }
            }
            
            // 标记为已加载
            state.value.isLoaded = true;
        } finally {
            state.value.loading = false;
        }
    }
    
    // 重置状态
    function resetState() {
        Object.assign(state.value, initState());
    }

    return {
        state,
        isLoaded,
        loading,
        hasIdentityInfo,
        hasPersonalInfo,
        hasContactInfo,
        hasOtherData,
        setUserInfo,
        resetState
    };
}, {
    persist: {
        key: 'user-info-store',
        storage: localStorage,
        paths: ['state.basicInfo', 'state.detailInfo', 'state.isLoaded']
    }
});